package com.ddpt.permission.dubbo;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lh.center.common.constant.GlobalConstant;
import com.lh.center.common.constant.RedisPrefix;
import com.lh.center.common.util.AssertUtil;
import com.lh.center.permission.api.dubbo.DubboAutoLoginService;
import com.lh.center.permission.api.entity.MerchantAdminUser;
import com.lh.center.permission.api.session.MerchantSessionUser;
import com.lh.center.permission.api.session.UserSessionUser;
import com.lh.center.permission.service.MerchantAdminUserService;
import com.lh.center.permission.service.login.MerchantLoginServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 系统间切换时的自动登陆处理
 */
@DubboService
public class DubboAutoLoginServiceImpl implements DubboAutoLoginService {

    @Resource
    private MerchantLoginServiceImpl merchantLoginService;

    @Resource
    private MerchantAdminUserService merchantAdminUserService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public MerchantSessionUser merchantAutoLogin(Long merchantId) {
        MerchantAdminUser user = merchantAdminUserService.get(Wrappers.lambdaQuery(MerchantAdminUser.class)
                .eq(MerchantAdminUser::getMerchantId, merchantId)
                .eq(MerchantAdminUser::getType, GlobalConstant.ZERO)
        );
        AssertUtil.isNull(user,"商户不存在");
        return merchantLoginService.autoLogin(merchantId, user.getUsername(), user.getRandomSecret());
    }

    @Override
    public void userAutoLogin(UserSessionUser user, String token, String code) {
        // 缓存 code 和 token 关系
        stringRedisTemplate.opsForValue().set(RedisPrefix.OPEN_USER_ACCESS_CODE + code, token, 30, TimeUnit.MINUTES);

        stringRedisTemplate.opsForValue().set(RedisPrefix.USER_ADMIN_USER_TOKEN + token, JSONUtil.toJsonStr(user), 1, TimeUnit.DAYS);
    }
}
